package com.study.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MqttTemplate {

	private static final Logger log = LoggerFactory.getLogger(MqttTemplate.class);

	private final MqttClient mqttClient;

	public MqttTemplate(MqttClient mqttClient) {
		this.mqttClient = mqttClient;
	}

	private static void printMessage(String topic, byte[] mqttMessage, int qos, boolean retained) {
		log.debug("Publishing message to topic :[{}], qos :[{}], retained :[{}]",
				new Object[] { topic, Integer.valueOf(qos), Boolean.valueOf(retained) });
		log.debug(">> :[{}]", new String(mqttMessage));
	}

	public void publish(String topic, MqttMessage mqttMessage) {
		if (log.isDebugEnabled()) {
			printMessage(topic, mqttMessage.getPayload(), mqttMessage.getQos(), mqttMessage.isRetained());
		}
		try {
			this.mqttClient.publish(topic, mqttMessage);
		} catch (MqttException e) {
			throw new MqttRuntimeException(e);
		}
	}

	public void publish(String topic, byte[] payload, int qos, boolean retained) {
		if (log.isDebugEnabled()) {
			printMessage(topic, payload, qos, retained);
		}
		try {
			this.mqttClient.publish(topic, payload, qos, retained);
		} catch (MqttException e) {
			throw new MqttRuntimeException(e);
		}
	}

	public void publish(String topic, byte[] payload) {
		publish(topic, payload, 0, false);
	}

}
